import React, { useState, useEffect } from 'react';
import {
  Card,
  Row,
  Col,
  Typography,
  Progress,
  Tag,
  Button,
  Space,
  Divider,
  Modal,
  List,
  Alert,
  Statistic,
  Badge
} from 'antd';
import {
  ClockCircleOutlined,
  EnvironmentOutlined,
  SearchOutlined,
  ThunderboltOutlined,
  MedicineBoxOutlined,
  HomeOutlined,
  LogoutOutlined
} from '@ant-design/icons';
import { GameSession, ActionType, Position, Room, Enemy, Container } from '../types/game';
import { SessionManager } from '../utils/sessionManager';
import { CITY_RUINS_MAP } from '../data/mapConfigs';
import { LootCalculator } from '../data/containerConfigs';

const { Text, Paragraph } = Typography;

interface SessionScreenProps {
  session: GameSession;
  onActionExecuted: (
    actionType: ActionType,
    targetPosition?: Position,
    targetEnemy?: Enemy,
    containerId?: string
  ) => void;
  onExitSession: () => void;
}

const SessionScreen: React.FC<SessionScreenProps> = ({
  session,
  onActionExecuted,
  onExitSession
}) => {
  const [selectedAction, setSelectedAction] = useState<ActionType | null>(null);
  const [actionModalVisible, setActionModalVisible] = useState(false);
  const [currentRoom, setCurrentRoom] = useState<Room | null>(null);
  const [availableRooms, setAvailableRooms] = useState<Room[]>([]);
  const [roomContainers, setRoomContainers] = useState<Container[]>([]);
  const [timeProgress, setTimeProgress] = useState(100);

  useEffect(() => {
    // 更新当前房间信息
    const room = SessionManager.getCurrentRoom(session);
    setCurrentRoom(room);

    // 更新可移动房间
    const rooms = SessionManager.getAvailableRooms(session);
    setAvailableRooms(rooms);

    // 更新房间容器
    const containers = SessionManager.getRoomContainers(session);
    setRoomContainers(containers);

    // 更新时间进度
    const progress = (session.remainingTime / session.maxTime) * 100;
    setTimeProgress(progress);
  }, [session]);

  const handleActionClick = (actionType: ActionType) => {
    setSelectedAction(actionType);
    setActionModalVisible(true);
  };

  const executeAction = (targetPosition?: Position, targetEnemy?: Enemy, containerId?: string) => {
    if (selectedAction) {
      onActionExecuted(selectedAction, targetPosition, targetEnemy, containerId);
      setActionModalVisible(false);
      setSelectedAction(null);
    }
  };

  const renderActionModal = () => {
    if (!selectedAction || !currentRoom) return null;

    switch (selectedAction) {
      case ActionType.MOVE:
        return (
          <Modal
            title="选择移动位置"
            open={actionModalVisible}
            onCancel={() => setActionModalVisible(false)}
            footer={null}
            width={600}
          >
            <List
              dataSource={availableRooms}
              renderItem={(room) => (
                <List.Item
                  actions={[
                    <Button
                      type="primary"
                      onClick={() => {
                        // 构建目标位置
                        const zone = CITY_RUINS_MAP.zones.find(z => z.id === session.currentPosition.zoneId);
                        let targetPosition: Position | undefined;
                        
                        if (zone) {
                          // 找到房间所在的建筑和楼层
                          for (const building of zone.buildings) {
                            for (const floor of building.floors) {
                              if (floor.rooms.find(r => r.id === room.id)) {
                                targetPosition = {
                                  mapId: session.currentPosition.mapId,
                                  zoneId: session.currentPosition.zoneId,
                                  buildingId: building.id,
                                  floorId: floor.id,
                                  roomId: room.id
                                };
                                break;
                              }
                            }
                            if (targetPosition) break;
                          }
                        }
                        
                        executeAction(targetPosition);
                      }}
                    >
                      移动
                    </Button>
                  ]}
                >
                  <List.Item.Meta
                    title={
                      <Space>
                        {room.name}
                        {room.isExtractionPoint && <Tag color="green">撤离点</Tag>}
                        {room.enemies.length > 0 && <Tag color="red">有敌人</Tag>}
                        {room.hasLoot && !room.searched && <Tag color="blue">可搜索</Tag>}
                      </Space>
                    }
                    description={room.description}
                  />
                </List.Item>
              )}
            />
          </Modal>
        );

      case ActionType.ZONE_TRAVEL:
        const zoneTransitions = SessionManager.getZoneTransitions(session);
        return (
          <Modal
            title="选择移动区域"
            open={actionModalVisible}
            onCancel={() => setActionModalVisible(false)}
            footer={null}
            width={600}
          >
            {zoneTransitions.length === 0 ? (
              <Alert message="当前区域没有通向其他区域的通道" type="info" />
            ) : (
              <List
                dataSource={zoneTransitions}
                renderItem={(transition) => {
                  const targetZone = CITY_RUINS_MAP.zones.find(z => z.id === transition.targetZone);
                  return (
                    <List.Item
                      actions={[
                        <Button
                          type="primary"
                          onClick={() => {
                            // 构建目标位置 - 移动到目标区域的第一个房间
                            const targetZoneData = CITY_RUINS_MAP.zones.find(z => z.id === transition.targetZone);
                            if (targetZoneData) {
                              const firstBuilding = targetZoneData.buildings[0];
                              const firstFloor = firstBuilding.floors[0];
                              const firstRoom = firstFloor.rooms[0];
                              
                              const targetPosition: Position = {
                                mapId: session.currentPosition.mapId,
                                zoneId: targetZoneData.id,
                                buildingId: firstBuilding.id,
                                floorId: firstFloor.id,
                                roomId: firstRoom.id
                              };
                              
                              executeAction(targetPosition);
                            }
                          }}
                        >
                          移动到区域
                        </Button>
                      ]}
                    >
                      <List.Item.Meta
                        title={
                          <Space>
                            <Text strong>通过 {transition.room.name}</Text>
                            <Text>前往 {targetZone?.name}</Text>
                          </Space>
                        }
                        description={
                          <Space direction="vertical">
                            <Text>通道描述: {transition.room.description}</Text>
                            <Text>目标区域: {targetZone?.description}</Text>
                            <Text type="warning">移动到其他区域需要消耗更多时间 (5分钟)</Text>
                          </Space>
                        }
                      />
                    </List.Item>
                  );
                }}
              />
            )}
          </Modal>
        );

      case ActionType.ATTACK:
        const activeEnemies = currentRoom.enemies.filter(enemy => !enemy.defeated);
        return (
          <Modal
            title="选择攻击目标"
            open={actionModalVisible}
            onCancel={() => setActionModalVisible(false)}
            footer={null}
            width={600}
          >
            {activeEnemies.length === 0 ? (
              <Alert message="当前房间没有敌人" type="info" />
            ) : (
              <List
                dataSource={activeEnemies}
                renderItem={(enemy) => (
                  <List.Item
                    actions={[
                      <Button
                        type="primary"
                        danger
                        onClick={() => executeAction(undefined, enemy)}
                      >
                        攻击
                      </Button>
                    ]}
                  >
                    <List.Item.Meta
                      title={enemy.name}
                      description={
                        <Space direction="vertical" size={4}>
                          <Text>血量: {enemy.health}/{enemy.maxHealth}</Text>
                          <Text>攻击力: {enemy.attack}</Text>
                          <Text>防御力: {enemy.defense}</Text>
                        </Space>
                      }
                    />
                  </List.Item>
                )}
              />
            )}
          </Modal>
        );

      case ActionType.SEARCH:
        return (
          <Modal
            title="搜索露天区域"
            open={actionModalVisible}
            onCancel={() => setActionModalVisible(false)}
            onOk={() => executeAction()}
            okText="开始搜索"
            cancelText="取消"
          >
            <Space direction="vertical" size={16}>
              <Alert
                message="搜索提示"
                description="搜索将消耗 3分钟，寻找房间内散落的物品。"
                type="info"
              />
              {currentRoom.searched && (
                <Alert message="此房间的露天区域已经搜索过了" type="warning" />
              )}
              {!currentRoom.hasLoot && (
                <Alert message="此房间看起来没有什么散落的物品" type="warning" />
              )}
            </Space>
          </Modal>
        );

      case ActionType.SEARCH_CONTAINER:
        const searchableContainers = roomContainers.filter(c => !c.searched);
        return (
          <Modal
            title="选择要搜索的容器"
            open={actionModalVisible}
            onCancel={() => setActionModalVisible(false)}
            footer={null}
            width={700}
          >
            {searchableContainers.length === 0 ? (
              <Alert message="当前房间没有可搜索的容器" type="info" />
            ) : (
              <List
                dataSource={searchableContainers}
                renderItem={(container) => {
                  const containerType = LootCalculator.getContainerType(container.typeId);
                  const containerName = container.name || containerType?.name || '未知容器';
                  const searchTime = containerType?.searchTime || 0;
                  
                  return (
                    <List.Item
                      actions={[
                        <Button
                          type="primary"
                          onClick={() => executeAction(undefined, undefined, container.id)}
                          disabled={Boolean(container.locked && container.requiredKey && 
                            !session.broughtItems.some(item => item.id === container.requiredKey) &&
                            !session.foundItems.some(item => item.id === container.requiredKey))
                          }
                        >
                          {container.locked && container.requiredKey ? '解锁并搜索' : '搜索'}
                        </Button>
                      ]}
                    >
                      <List.Item.Meta
                        title={
                          <Space>
                            <Text strong>{containerType?.icon} {containerName}</Text>
                            {container.locked && (
                              <Tag color="red" icon="🔒">已锁定</Tag>
                            )}
                            <Tag color={containerType?.rarity === 'legendary' ? 'red' : 
                                      containerType?.rarity === 'epic' ? 'purple' :
                                      containerType?.rarity === 'rare' ? 'blue' :
                                      containerType?.rarity === 'uncommon' ? 'green' : 'default'}>
                              {containerType?.rarity}
                            </Tag>
                          </Space>
                        }
                        description={
                          <Space direction="vertical" size={4}>
                            <Text>{containerType?.description}</Text>
                            <Text type="secondary">搜索时间: {Math.floor(searchTime / 60)}分{searchTime % 60}秒</Text>
                            {container.locked && container.requiredKey && (
                              <Text type="warning">需要: {container.requiredKey}</Text>
                            )}
                          </Space>
                        }
                      />
                    </List.Item>
                  );
                }}
              />
            )}
          </Modal>
        );

      case ActionType.EXTRACT:
        return (
          <Modal
            title="撤离确认"
            open={actionModalVisible}
            onCancel={() => setActionModalVisible(false)}
            onOk={() => executeAction()}
            okText="确认撤离"
            cancelText="取消"
            okType="primary"
          >
            <Space direction="vertical" size={16}>
              <Alert
                message="撤离提示"
                description="撤离后将结束当前对局，带出所有找到的物品。确认撤离吗？"
                type="success"
              />
              <div>
                <Text strong>已找到物品: </Text>
                <Text>{session.foundItems.length} 件</Text>
              </div>
            </Space>
          </Modal>
        );

      default:
        return (
          <Modal
            title="执行行动"
            open={actionModalVisible}
            onCancel={() => setActionModalVisible(false)}
            onOk={() => executeAction()}
            okText="确认"
            cancelText="取消"
          >
            <Alert
              message={`将执行: ${selectedAction}`}
              description={`此行动将消耗一定时间`}
              type="info"
            />
          </Modal>
        );
    }
  };

  if (!currentRoom) {
    return <div>加载中...</div>;
  }

  const timeColor = timeProgress > 50 ? 'success' : timeProgress > 20 ? 'normal' : 'exception';
  const activeEnemies = currentRoom.enemies.filter(enemy => !enemy.defeated);

  return (
    <div style={{ padding: '24px', minHeight: '100vh', backgroundColor: '#141414' }}>
      <Row gutter={[24, 24]}>
        {/* 状态栏 */}
        <Col span={24}>
          <Card>
            <Row gutter={[16, 16]} align="middle">
              <Col flex="auto">
                <Space size="large">
                  <Statistic
                    title="剩余时间"
                    value={SessionManager.formatTime(session.remainingTime)}
                    prefix={<ClockCircleOutlined />}
                    valueStyle={{ 
                      color: timeProgress > 20 ? '#1890ff' : '#ff4d4f',
                      fontSize: '24px'
                    }}
                  />
                  <Divider type="vertical" style={{ height: '40px' }} />
                  <div>
                    <Text type="secondary">当前位置</Text>
                    <br />
                    <Text strong>
                      <EnvironmentOutlined /> {SessionManager.getLocationDescription(session.currentPosition)}
                    </Text>
                    <br />
                    <Space size="small">
                      <Tag color={CITY_RUINS_MAP.zones.find(z => z.id === session.currentPosition.zoneId)?.color || 'default'}>
                        {CITY_RUINS_MAP.zones.find(z => z.id === session.currentPosition.zoneId)?.name}
                      </Tag>
                      {SessionManager.getZoneTransitions(session).length > 0 && (
                        <Tag color="purple" icon={<EnvironmentOutlined />}>
                          可移动到其他区域
                        </Tag>
                      )}
                    </Space>
                  </div>
                </Space>
              </Col>
              <Col>
                <Button 
                  danger 
                  icon={<LogoutOutlined />}
                  onClick={onExitSession}
                >
                  退出对局
                </Button>
              </Col>
            </Row>
            <div style={{ marginTop: 16 }}>
              <Progress 
                percent={timeProgress} 
                status={timeColor}
                showInfo={false}
                strokeColor={{
                  '0%': '#87d068',
                  '50%': '#faad14',
                  '100%': '#ff4d4f',
                }}
              />
            </div>
          </Card>
        </Col>

        {/* 房间信息 */}
        <Col span={12}>
          <Card
            title={
              <Space>
                <EnvironmentOutlined />
                {currentRoom.name}
                {currentRoom.isExtractionPoint && <Tag color="green">撤离点</Tag>}
              </Space>
            }
          >
            <Space direction="vertical" size={12} style={{ width: '100%' }}>
              <Paragraph>{currentRoom.description}</Paragraph>
              
              <Row gutter={[8, 8]}>
                <Col>
                  <Badge 
                    count={activeEnemies.length} 
                    color="red"
                    showZero={false}
                  >
                    <Tag icon={<ThunderboltOutlined />} color="red">
                      敌人
                    </Tag>
                  </Badge>
                </Col>
                <Col>
                  <Tag 
                    icon={<SearchOutlined />} 
                    color={currentRoom.hasLoot && !currentRoom.searched ? "blue" : "default"}
                  >
                    露天: {currentRoom.searched ? "已搜索" : currentRoom.hasLoot ? "可搜索" : "无物品"}
                  </Tag>
                </Col>
                <Col>
                  <Badge 
                    count={SessionManager.getSearchableContainers(session).length} 
                    color="cyan"
                    showZero={false}
                  >
                    <Tag icon={<SearchOutlined />} color="cyan">
                      容器
                    </Tag>
                  </Badge>
                </Col>
              </Row>

              {activeEnemies.length > 0 && (
                <Alert
                  message={`警告: 房间内有 ${activeEnemies.length} 个敌人！`}
                  type="warning"
                  showIcon
                />
              )}
            </Space>
          </Card>
        </Col>

        {/* 行动选择 */}
        <Col span={12}>
          <Card title="可执行行动">
            <Row gutter={[12, 12]}>
              <Col span={12}>
                <Button
                  block
                  size="large"
                  icon={<EnvironmentOutlined />}
                  onClick={() => handleActionClick(ActionType.MOVE)}
                  disabled={availableRooms.length === 0}
                >
                  移动 (1分钟)
                </Button>
              </Col>
              <Col span={12}>
                <Button
                  block
                  size="large"
                  icon={<EnvironmentOutlined />}
                  onClick={() => handleActionClick(ActionType.ZONE_TRAVEL)}
                  disabled={SessionManager.getZoneTransitions(session).length === 0}
                  style={{ backgroundColor: '#722ed1', borderColor: '#722ed1' }}
                  type="primary"
                >
                  区域移动 (5分钟)
                </Button>
              </Col>
              <Col span={12}>
                <Button
                  block
                  size="large"
                  icon={<SearchOutlined />}
                  onClick={() => handleActionClick(ActionType.SEARCH)}
                  disabled={!currentRoom.hasLoot || currentRoom.searched}
                >
                  搜索露天 (3分钟)
                </Button>
              </Col>
              <Col span={12}>
                <Button
                  block
                  size="large"
                  icon={<SearchOutlined />}
                  onClick={() => handleActionClick(ActionType.SEARCH_CONTAINER)}
                  disabled={SessionManager.getSearchableContainers(session).length === 0}
                  style={{ backgroundColor: '#13c2c2', borderColor: '#13c2c2', color: 'white' }}
                >
                  搜索容器
                </Button>
              </Col>
              <Col span={12}>
                <Button
                  block
                  size="large"
                  icon={<ThunderboltOutlined />}
                  onClick={() => handleActionClick(ActionType.ATTACK)}
                  disabled={activeEnemies.length === 0}
                  danger={activeEnemies.length > 0}
                >
                  战斗 (2分钟)
                </Button>
              </Col>
              <Col span={12}>
                <Button
                  block
                  size="large"
                  icon={<MedicineBoxOutlined />}
                  onClick={() => handleActionClick(ActionType.HEAL)}
                  disabled={session.broughtItems.filter(item => item.type === 'consumable').length === 0}
                >
                  治疗 (1.5分钟)
                </Button>
              </Col>
              <Col span={12}>
                <Button
                  block
                  size="large"
                  icon={<HomeOutlined />}
                  onClick={() => handleActionClick(ActionType.REST)}
                >
                  休息 (5分钟)
                </Button>
              </Col>
              <Col span={12}>
                <Button
                  block
                  size="large"
                  type="primary"
                  icon={<LogoutOutlined />}
                  onClick={() => handleActionClick(ActionType.EXTRACT)}
                  disabled={!session.canExtract}
                >
                  撤离 (30秒)
                </Button>
              </Col>
            </Row>
          </Card>
        </Col>

        {/* 背包和发现物品 */}
        <Col span={24}>
          <Row gutter={[24, 24]}>
            <Col span={12}>
              <Card title="携带物品" size="small">
                <List
                  size="small"
                  dataSource={session.broughtItems}
                  renderItem={(item) => (
                    <List.Item>
                      <Space>
                        <Tag color="blue">{item.name}</Tag>
                        <Text type="secondary">x{item.quantity}</Text>
                      </Space>
                    </List.Item>
                  )}
                  locale={{ emptyText: '未携带任何物品' }}
                />
              </Card>
            </Col>
            <Col span={12}>
              <Card title="发现物品" size="small">
                <List
                  size="small"
                  dataSource={session.foundItems}
                  renderItem={(item) => (
                    <List.Item>
                      <Space>
                        <Tag color="green">{item.name}</Tag>
                        <Text type="secondary">x{item.quantity}</Text>
                      </Space>
                    </List.Item>
                  )}
                  locale={{ emptyText: '尚未发现任何物品' }}
                />
              </Card>
            </Col>
          </Row>
        </Col>
      </Row>

      {renderActionModal()}
    </div>
  );
};

export default SessionScreen;